package cn.jdemo.guava.caches;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;

import java.time.Duration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class Demo02 {

    private static final CacheBuilder<Object, Object> cacheBuilder =
            CacheBuilder.newBuilder().
                    expireAfterAccess(Duration.ofSeconds(1L))
                    .removalListener((t)->{
                        System.out.println(t.getCause());
                    });

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        test01();
    }

    public static void test01() throws InterruptedException, ExecutionException {

        LoadingCache<Object, Object> build1 = cacheBuilder.build(new CacheLoader<Object, Object>() {
            @Override
            public Object load(Object key) throws Exception {
                return key.toString() + "1";
            }
        });

        Object val = build1.get("a", () -> {
            return "ok";
        });
        Object val2 = build1.get("b");
        System.out.println("val:"+val);
        System.out.println("val2:"+val2);
        Object val3 = build1.get("a");
        System.out.println("val3:"+val3);
    }
}
